package com.uduew.sjd.request;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.uduew.sjd.api.UploadFileApi;
import com.uduew.sjd.bean.HttpBean;
import com.uduew.sjd.net.AsyncTask;
import com.uduew.sjd.net.DataRepository;
import com.uduew.sjd.net.DataResult;
import com.uduew.sjd.net.ResponseStatus;
import com.uduew.sjd.net.ResultSource;
import com.kunminx.architecture.domain.message.MutableResult;
import com.kunminx.architecture.domain.message.Result;

import org.jetbrains.annotations.NotNull;

import java.io.File;

import io.reactivex.disposables.Disposable;


public class UploadFileRequester extends Requester implements DefaultLifecycleObserver {

    private final MutableResult<DataResult<HttpBean<UploadFileApi.UploadBean>>> result = new MutableResult<>();

    public Result<DataResult<HttpBean<UploadFileApi.UploadBean>>> getResult() {
        return result;
    }

    private Disposable mDisposable;

    public void request(LifecycleOwner lifecycleOwner, File file) {
        UploadFileApi updateImageApi = new UploadFileApi(file);
        DataRepository.getInstance().uploadFile(lifecycleOwner, updateImageApi).subscribe(new AsyncTask.Observer<DataResult<HttpBean<UploadFileApi.UploadBean>>>() {
            @Override
            public void onNext(DataResult<HttpBean<UploadFileApi.UploadBean>> dataResult) {
                if (!dataResult.getResponseStatus().isSuccess()) {
                    return;
                }
                ResponseStatus responseStatus = new ResponseStatus(dataResult.getResult().getMsg(), dataResult.getResult().isRequestSuccess(), ResultSource.NETWORK);
                result.postValue(new DataResult<>(dataResult.getResult(), responseStatus));
            }

            @Override
            public void onSubscribe(Disposable d) {
//                input(UploadImageIntent.OnLoading(true));
            }

            @Override
            public void onError(Throwable e) {
                ResponseStatus responseStatus = new ResponseStatus(e.getMessage(), false, ResultSource.NETWORK);
                result.postValue(new DataResult<>(null, responseStatus));
            }

            @Override
            public void onComplete() {
                AsyncTask.Observer.super.onComplete();
            }
        });
    }

    public void cancelLogin() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }

    @Override
    public void onStop(@NonNull @NotNull LifecycleOwner owner) {
        cancelLogin();
    }
}
